const indexModel = require('../models/indexModel');
const utils = require('../utils/index');
let myGlobal = {};


exports.index = (req, res) => {
    indexModel.index().then(function(data) {
        // console.log(data);
        data[3] = utils.arrFormat2(data[3]);
        let result = {
            menus: data[0],
            banners: data[1],
            types: data[2],
            articals: data[3],
            user: req.session.user2
        }
        myGlobal.menus = data[0];
        res.render('index', result);
    })
}

//娴前台登录
exports.loginPage = function(req, res) {
    res.render('login')
}

exports.registerPage = function(req, res) {

    res.render('register')
}

exports.login = function(req, res) {
        indexModel.login(req.body).then(function(data) {
            req.session.user2 = data[0];
            res.redirect('/')
        })
 }
exports.register = function(req, res) {
        indexModel.register(req.body).then(function(data) {

            res.redirect('/login')
        })
 }
    //文章详情页
exports.detailPage = function(req, res) {
        console.log(req.params.id);

        indexModel.getOneArtical(req.params.id).then(function(data) {
            console.log(data);
            res.render('detail', { artical: data[0], menus: myGlobal.menus, user: req.session.user2 });
        })
    }
    //发布文章
exports.createArtical = function(req, res) {
    if (req.session.user2) {
        indexModel.getAllClass().then(function(data) {
            res.render('create', { menus: myGlobal.menus, user: req.session.user2, types: data })
        })

    } else {
        res.redirect('/login')
    }
}

exports.sendArtical = function(req, res) {
    indexModel.sendArtical(req.body).then(function(data) {
        if (data.affectedRows > 0) {
            res.redirect('/')
        }
    })
}